package com.computer.network.service.impl;

import com.computer.network.service.RedisService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisServiceImpl implements RedisService {
    @Resource
    RedisTemplate<String, UserDetails> redisTemplate;
    //过期时间,单位s
    @Value("${jwt.data.expiration}")
    private String expiration;
    //锁续命 单位s
    @Value("${values.redisTimeLast}")
    private double redisTimeLast;

    @Override
    public void LoginAddRedis(String K, UserDetails V) {
        //设置时间为30分钟
        redisTemplate.opsForValue().set(K, V, Long.parseLong(expiration) * 1000, TimeUnit.MILLISECONDS);
    }

    @Override
    public Boolean LoginDeleteRedis(String K) {
        final Boolean delete = redisTemplate.delete(K);
        return delete;
    }

    @Override
    public UserDetails LoginSelectRedis(String K) {
        UserDetails s = redisTemplate.opsForValue().get(K);
        return s;
    }

    @Override
    public Boolean LoginIsRedis(String K) {
        UserDetails token = redisTemplate.opsForValue().get(K);
        if (token != null) {
            return true;
        }
        return false;
    }

    @Override
    public double TimeRedis(String K) {
        //获取锁时间
        double expire = redisTemplate.getExpire(K);
        //时间小于一半，执行锁续命
        if (expire / Integer.valueOf(expiration) <= redisTimeLast) {
            redisTemplate.delete(K);
            UserDetails userDetails = redisTemplate.opsForValue().get(K);
            redisTemplate.opsForValue().setIfAbsent(K, userDetails, Long.parseLong(expiration), TimeUnit.SECONDS);
        }
        return expire;
    }

}
